package com.whc.gulimall.cart.interceptor;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.whc.common.constant.SocialLoginConstant;
import com.whc.common.vo.SocialResponseVo;
import com.whc.gulimall.cart.constant.CartConstant;
import com.whc.gulimall.cart.vo.UserInfoTo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 自定义拦截器
 *
 * @author angaoen
 */
@Component
public class CartInterceptor implements HandlerInterceptor {

    /**
     * 当前线程可共享其中的数据
     */
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * 处理之前
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理
     * @return 结果
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取session
        HttpSession session = request.getSession();
        // 获取session中的指定内容
        SocialResponseVo responseVo = (SocialResponseVo) session
                .getAttribute(SocialLoginConstant.SOCIAL_LOGIN_CONSTANT);

        UserInfoTo userinfo = new UserInfoTo();

        // 已登录
        if (responseVo != null) {
            userinfo.setUserId(responseVo.getId());
        }

        // 获取指定cookie内的数据
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (CartConstant.USER_KEY.equals(cookie.getName())) {
                    userinfo.setUserKey(cookie.getValue());
                }
            }
        }

        // 如果走到这里，没有userKey，那么就需要创建一个临时userKey
        if (StrUtil.isEmpty(userinfo.getUserKey())) {
            userinfo.setUserKey(UUID.fastUUID().toString());
            userinfo.setIsTempUser(true);
        }

        // 把当前的元素放入到当前线程
        threadLocal.set(userinfo);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        // 如果是临时用户
        if (userInfoTo.getIsTempUser()) {
            Cookie cookie = new Cookie(CartConstant.USER_KEY, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.MAX_AGE);
            response.addCookie(cookie);
        }
    }
}
